package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.result.ServiceCallResponse;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.remote.ProductApiClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;


/**
 * 参数校验
 **/
@Slf4j
@Component
public class ValidateHandler extends AbstractTransHandler {

    @Autowired
    ProductApiClient productApiClient;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        ArrayList<Long> buyProductIds = new ArrayList<>();
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto cartProductDto : cartProductDtoList) {
            buyProductIds.add(cartProductDto.getProductId());
        }
        createOrderContext.setBuyProductIds(buyProductIds);

        for (Long buyProductId : buyProductIds) {
            ServiceCallResponse<Integer> productStatus = productApiClient.getProductStatus(buyProductId);
            Integer status = productStatus.getCallData();
            if (status == 0) {
                throw new BizException("商品已下架，请重新选购！");
            }
        }


        return true;
    }
}
